﻿using Jjb.ScoresRanks.Net5.API.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Jjb.ScoresRanks.Net5.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : BaseController
    {
        // GET api/<ValuesController>/5
        [HttpPost("/customer/{customerid}/score/{score}")]
        public JsonResult UpdateScore(long customerid, int score)
        {

            if (customerid < 0)
            {
                return new JsonResult(new ReturnEntity<int>
                {
                    code = 409,
                    msg = "customerid参数值错误",
                    data = -1
                });
            }

            if (score > 1000 || score < -1000)
            {
                return new JsonResult(new ReturnEntity<int>
                {
                    code = 409,
                    msg = "score参数值错误",
                    data = -1
                });
            }

            var model = customers.FirstOrDefault(x => x.CustomerID == customerid);
            var resultScore = 0;
            if (model is not null)
            {
                var oldScore = model.Score;

                model.Score += score;

                if (model.Score <= -1000)
                {
                    model.Score = -1000;
                } else if (model.Score >= 1000) {
                    model.Score = 1000;
                }
                resultScore = model.Score;
            }
            else
            {
                if (score > 0)
                {
                    customers.Add(new Model.Customer
                    {
                        CustomerID = customerid,
                        Score = score
                    });
                    resultScore = score;
                }
                else
                {
                    return new JsonResult(new ReturnEntity<int>
                    {
                        code = 409,
                        msg = "customerid不存在，score参数值不能为负数",
                        data = -1
                    });
                }
            }

            //更新数据排名
            UpdateRank();

            return new JsonResult(new ReturnEntity<int>()
            {
                code = 200,
                msg = "操作成功",
                data = resultScore
            });
        }

        private void UpdateRank() {

            var list = customers.OrderByDescending(x => x.Score).ToList();
            var newIndex = 0;
            foreach (var item in list)
            {
                item.Rank = ++newIndex;
            }
            customers.RemoveAll(x => 1==1);
            customers = list;
            var aa = 0;
        }


        [HttpGet("/leaderboard")]
        public JsonResult GetCustomersByRank(int start, int end)
        {
            var listCount = customers.Count;
            if (start <= 0 && start > listCount)
            {
                return new JsonResult(new ReturnEntity<string>()
                {
                    code = 409,
                    msg = "start值不在当前排行榜！",
                    data = ""
                });
            }
            if (end <= 0 && end > listCount)
            {
                return new JsonResult(new ReturnEntity<string>()
                {
                    code = 409,
                    msg = "end值不在当前排行榜！",
                    data = ""
                });
            } 

            if (start > end)
            {
                return new JsonResult(new ReturnEntity<string>()
                {
                    code = 409,
                    msg = "start或end值不正确，请核实！",
                    data = ""
                });
            }

            var findCount = 0;
            if (start == end)
            {
                findCount = 1;
            }

            var startEntity = customers.FirstOrDefault(x => x.Rank == start);
            if (startEntity is null)
            {
                return new JsonResult(new ReturnEntity<string>()
                {
                    code = 409,
                    msg = "未找到start对应的实体数据！",
                    data = ""
                });
            }
            var startIndex = customers.IndexOf(startEntity);

            var endEntity = customers.FirstOrDefault(x=>x.Rank == end);
            if (endEntity is null)
            {
                findCount = listCount;
            }
            else
            {
                var endIndex = customers.IndexOf(endEntity);

                findCount = (endIndex - startIndex)+1;
            }
            var list = customers.GetRange(startIndex, findCount);

            return new JsonResult(new ReturnEntity<List<Customer>>()
            {
                code = 200,
                msg = "获取成功",
                data = list
            });
        }

        [HttpGet("/leaderboard/{customerid}")]
        public JsonResult GetCustomersByCustomerId(long customerid, int high=0,int low=0) {
            var resultList = new List<Customer>();
            var entity = customers.FirstOrDefault(x => x.CustomerID==customerid);
            if (entity is null)
            {
                return new JsonResult(new ReturnEntity<List<Customer>>()
                {
                    code = 409,
                    msg = $"{customerid}对应实体不存在，请朴实！",
                    data = null
                });
            }

            if (high < 0 || low < 0)
            {
                return new JsonResult(new ReturnEntity<List<Customer>>()
                {
                    code = 409,
                    msg = $"high或low值不允许为负数！",
                    data = null
                });
            }

            var startIndex = 0;
            var endIndex = 0;
            var index = customers.IndexOf(entity);
            if (low > 0)
            {
                var tempIndex = index + low;
                endIndex = tempIndex > customers.Count ? customers.Count : tempIndex;
            }
            if (high > 0)
            {
                var tempIndex = index-high;
                startIndex = tempIndex<=0 ? 0 : tempIndex;
            }
            var listCount = endIndex - startIndex;
            if (listCount < customers.Count)
            {
                listCount += 1;
            }


            resultList = customers.GetRange(startIndex, listCount);

            return new JsonResult(new ReturnEntity<List<Customer>>()
            {
                code = 200,
                msg = $"获取数据成功",
                data = resultList
            });
        } 
    }
}
